#include "stdafx.h"
#include "service\storage\file\SportFileService.h"
#include "service\storage\file\DivisionFileService.h"
#include "model\BaseModel.h"
#include "model\Sport.h"


SportFileService::SportFileService() {

}


SportFileService::SportFileService(const std::string fname,
                                   const std::ios::openmode mode)
    : BaseFileService(fname, mode) {

}


SportFileService::SportFileService(std::fstream& file) : BaseFileService(file) {

}


SportFileService::~SportFileService() {

}


BaseFileService& SportFileService::Load(Sport* sport) {
  file() >> *sport;
  return *this;
}

BaseFileService& SportFileService::Save(const Sport& sport) {
  file() << sport << '\n';
  return *this;
}

BaseFileService& SportFileService::LoadFile(TCollection<Sport> *sports) {
  Sport sport;
  while (file() >> sport) {
    int numdivisions;
    file() >> numdivisions;
    file().ignore();
    DivisionFileService dfs(file());
    for (int i = 0; i < numdivisions; ++i) {
      Division division;
      dfs.Load(&division);
      if (division.Validate())
        sport.AddDivision(division);
    }
    if (sport.Validate())
      sports->Add(sport);
  }
  return *this;
}


BaseFileService& SportFileService::SaveFile(const TCollection<Sport> *sports) {
  TCollection<Sport>::CollectionPair sportiters = sports->GetCollection();
  for (; sportiters.first != sportiters.second; ++sportiters.first) {
    Save(*sportiters.first);
    file() << sportiters.first->NumDivisions() << '\n';
    TCollection<Division>::CollectionPair diviters = sportiters.first->GetDivisions();
    DivisionFileService dfs(file());
    for (; diviters.first != diviters.second; ++diviters.first) {
      dfs.Save(*diviters.first);
    }
  }
  return *this;
}